package com.rzjm.api.netty.charger;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: programme
 * @description: 创建全局Map存放现已连接服务器
 * @author: qiu bo yang
 * @create: 2020-10-09 09:57
 **/
@Slf4j
@Component
@Data
public class SocketPool {

    public static Integer HeartSeconds = 60;

    public static Integer timeOut = 90;

    /*添加代码 begin*/
    private static SocketPool socketPool;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @PostConstruct
    public void init(){
        socketPool = this;
        socketPool.redisTemplate = this.redisTemplate;
    }

    private static final ConcurrentHashMap<String, ClientSocket> ONLINE_SOCKET_MAP = new ConcurrentHashMap<>();

    /**
     *  添加 连接
     * @param clientSocket
     */
    public static void add(ClientSocket clientSocket) {
        if (clientSocket != null && !clientSocket.getId().isEmpty()){
            ONLINE_SOCKET_MAP.put(clientSocket.getChannel().id().asShortText(), clientSocket);
        }
        System.out.println("当前在线设备数：" + ONLINE_SOCKET_MAP.size());
    }

    public static void remove(String key) {
        if (!key.isEmpty()){
            ClientSocket clientSocket = ONLINE_SOCKET_MAP.get(key);
            if(clientSocket!=null){
                ONLINE_SOCKET_MAP.remove(key);
                clientSocket.getChannel().close();
                System.out.println(key + " 已删除");
            }
        }
    }

    public static ClientSocket getClient(String id){
        return ONLINE_SOCKET_MAP.get(id);
    }

    /**
     *  设备终端信息
     * @param deviceNum
     * @return
     */
    public static List<ClientSocket> getClientByDeviceNum(String deviceNum){
        List<ClientSocket> list = new ArrayList<>();
        System.out.println("getClientByDeviceNum: " + deviceNum);
        for (Map.Entry<String, ClientSocket> entry : ONLINE_SOCKET_MAP.entrySet()) {
            ClientSocket clientSocketTemp = entry.getValue();
//            System.out.println("设备编号: " + clientSocketTemp.getTerminalNum() + " =====  SessionId: " + clientSocketTemp.getId());
            if(clientSocketTemp.getTerminalNum() != null && clientSocketTemp.getTerminalNum().equals(deviceNum)){
                list.add(clientSocketTemp);
            }
        }
        return list;
    }

    public static void autoDelChannel(){
        ONLINE_SOCKET_MAP.forEach((k, v)->{
            ClientSocket clientSocket = v;
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(clientSocket.getLastDate());
            calendar.add(Calendar.SECOND, timeOut);
            long lastTime = calendar.getTimeInMillis();//最后连接时间，加上5分钟
            long nowTime = new Date().getTime();//当前时间
            String terminalNum = clientSocket.getTerminalNum();
            if(nowTime >= lastTime){//如果当前时间  要大于
//                ONLINE_SOCKET_MAP.remove(k);
//                clientSocket.getChannel().close();
//                System.out.println("已超时： " +k + " 已删除");
//                MessageDecode.updateDeviceOnlineState(terminalNum,0);
//                log.info("客户端：" + k +" ，已经超过2分钟没有交互，执行删除，最后连接时间：" + clientSocket.getLastDate() + " " + DateUtil.getTime());
            }
        });
    }
}
